<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class UserController extends Controller
{
    //登陆
    public function login(Request $request)
    {
        $input = $request->all();
        if($request->isMethod('post')){
            if($input['authcode']==Session::get('code')){
                if($admin = Admin::where(['username'=>$input['account'],'password'=>$input['password']])->first()){
                    if($admin->type!=3){
                        $admin->save();
                        $code = DB::table('b_distributorcode')->where('adminid',$admin->admin_id)->first();
                        if($code){
                            $admin->code = $code->distributorcode;
                        }else{
                            $admin->code = "没有生成邀请码";
                        }
                        Session::put("admin",$admin);
                        return redirect('/');
                    }else{
                        return back()->with('status',"用户已被删除");
                    }

                }else{
                    return back()->with('status','账号密码错误')->withInput($input);
                }
            }else {
                return back()->with('status' , '验证码错误')->withInput($input);
            }
        }
        return view("admin.login");
    }

    //登陆验证码
    public function authcode()
    {
        $code_str="1234567890";
        $code = '';
        for ($i = 0; $i < 4; $i++) {
            $code .= $code_str [mt_rand(0, strlen($code_str) - 1)];
        }
        $builder = new CaptchaBuilder($code);//new CaptchaBuilder($code);
        //可以设置图片宽高及字体
        $builder->build(150,32);
        //把内容存入session
        Session::flash('code', $code);
        //生成图片
        return response($builder->output())->header('Content-type','image/jpeg');
    }

    //登出
    public function logout()
    {
        Session::forget('admin');
        return redirect("login");
    }

    public function index()
    {
        $admin = Session::get('admin');
        return view("admin.index",[
            'admin'=>$admin,
        ]);
    }
    
}
